package com.web.controller.xg;

import com.core.dto.ExcutorDTO;
import com.core.dto.RefrigerationDTO;
import com.core.shared.DigitalHandle;
import com.service.XgService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * 兴国家电制冷
 *
 * @author lxf
 * @date 2018/5/2 16:32
 * To change this template use Editor | File and Code Templates.
 */
@Controller
@RequestMapping("/xg")
public class RefrigerationController {

    @Autowired
    private XgService xgService;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public ModelAndView index(Model model) {
        List<RefrigerationDTO> refrigerationDTOs = xgService.findAllRefrigeration();
        double allIncome = refrigerationDTOs.stream().mapToDouble(RefrigerationDTO::getIncomeForDouble).sum();
        double allExpenditure = refrigerationDTOs.stream().mapToDouble(RefrigerationDTO::getExpenditureForDouble).sum();
        BigDecimal allBalance = DigitalHandle.subtract(new BigDecimal(allIncome), new BigDecimal(allExpenditure));
        BigDecimal one = new BigDecimal("1");
        allBalance = allBalance.divide(one, 2, BigDecimal.ROUND_DOWN);
        model.addAttribute("allIncome", allIncome);
        model.addAttribute("allExpenditure", allExpenditure);
        model.addAttribute("allBalance", allBalance.doubleValue());
        return new ModelAndView("/xg/refrigeration", "refrigerationDTOs", refrigerationDTOs);
    }

    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public ModelAndView toUpdate(String id, Model model) {
        RefrigerationDTO refrigerationDTO;
        if (StringUtils.isNotEmpty(id)) {
            refrigerationDTO = xgService.findRefrigerationById(id);
            refrigerationDTO.setExcutorId(refrigerationDTO.getExcutor().getId());
        } else {
            refrigerationDTO = new RefrigerationDTO();
        }
        model.addAttribute("executorMaps", ExcutorDTO.toMaps(xgService.findAllExcutor()));
        return new ModelAndView("/xg/refrigerationUpdate", "refrigerationDTO", refrigerationDTO);
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String saveOrUpdate(RefrigerationDTO refrigerationDTO) {
        xgService.saveOrUpdateRefrigeration(refrigerationDTO);
        return "redirect:/xg/";
    }

    @RequestMapping(value = "/del/{id}", method = RequestMethod.GET)
    public String del(@PathVariable String id) {
        xgService.delRefrigeration(id);
        return "redirect:/xg/";
    }

}
